package com.atguigu.day06;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

public class Flink04_Window_WindowFun_Process {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.从端口读取数据并转为WaterSensor
        WindowedStream<WaterSensor, Tuple, TimeWindow> window = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                })
                //将相同id的数据聚合到一块
                .keyBy("id")
                //开启一个基于处理时间的滚动窗口  窗口大小5S
                .window(TumblingProcessingTimeWindows.of(Time.seconds(5)));
        //使用全窗口函数 processFun
        window.process(new ProcessWindowFunction<WaterSensor, String, Tuple, TimeWindow>() {
            @Override
            public void process(Tuple tuple, ProcessWindowFunction<WaterSensor, String, Tuple, TimeWindow>.Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                Integer vcSum = 0;
                for (WaterSensor element : elements) {
                    vcSum += element.getVc();
                }

                out.collect("计算结果："+tuple.toString() + "->" + vcSum+"窗口["+context.window().getStart()/1000+","+context.window().getEnd()/1000+")=====窗口数据个数："+elements.spliterator().estimateSize());
            }
        }).print();


        env.execute();
    }
}
